﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE80;
using System.Windows.Forms;
using System.Diagnostics;

namespace VSSpeeder
{
	public class CustomEventArgs : EventArgs
	{
		public Action<object> ToExecute { get; set; }
		public object Parameter { get; set; }
	}
	
	public sealed class AsyncController
	{
		private static readonly AsyncController _asyncController = new AsyncController();
		public static AsyncController Instance
		{
			get { return _asyncController; }
		}

		private AsyncController()
		{
			
		}

		private Control _routingControl;
		public void Initialize(DTE2 dte)
		{
			var hwnd = dte.MainWindow.HWnd;
			//var mainWindow = Control.FromHandle((IntPtr) hwnd);
			var nativeWindow = new System.Windows.Forms.NativeWindow();
			nativeWindow.AssignHandle((IntPtr) hwnd);
			//nativeWindow.
			_routingControl = new Control("VSSpeederRoutingControl", -1000, -1000, 1, 1);
			_routingControl.CreateControl();
		}

		public void ExecuteOnUiThread(Action<object> action, object parameter = null)
		{
			_routingControl.Invoke(new EventHandler(InternalExecuteOnUiThread), new CustomEventArgs() {ToExecute = action, Parameter = parameter});
		}
		private void InternalExecuteOnUiThread(object sender, EventArgs e)
		{
			try
			{
				CustomEventArgs args = sender as CustomEventArgs;
				args.ToExecute(args.Parameter);
			}
			catch (Exception ex)
			{
				Trace.WriteLine(ex.ToString());
			}
		}
	}
}
